<template>
  <c-select
    v-bind="$attrs"
    filterable
    :loading="loading"
    :value="value"
    :options="tableData"
    :props="props"
    @change="hangleChange"
  ></c-select>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  components: {},
  props: {
    value: {
      type: String,
      default: '',
    },
    isPro: {
      type: Boolean,
      default: false,
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      props: {
        value: 'agency_id',
        label: 'agency_name',
      },
      loading: false,
      tableName: 'credit_agency_info_view',
      tableData: [],
    }
  },
  computed: {
    ...mapGetters(['accessCreditAgency', 'clientId', 'user']),
    isUnion() {
      return this.user?.scopeArr?.includes('dirGuaPro') ?? false
    },
  },
  watch: {},
  created() {
    if (this.isUnion) {
      this.getAllCredit()
    } else {
      this.getData()
    }
  },
  mounted() {},
  methods: {
    getAllCredit() {
      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          this.tableName,
          {
            'agency_type.eq': 6,
            'scopes.notIn': 'dirGuaPro',
          },
          { create_time: 'desc' }
        )
        .then(res => {
          this.tableData = res?.data ?? []
        })
        .finally(() => {
          this.loading = false
        })
    },
    getData() {
      this.loading = true
      this.$api
        .getData(
          this.$serviceName,
          'credit_agency_access_view',
          {
            'agency_type.eq': 6,
            'access_agency_id.eq': this.clientId,
            'service_agency_lever.eq': this.isPro ? 1 : '',
          },
          { create_time: 'desc' }
        )
        .then(res => {
          this.tableData = (res?.data ?? []).map(item => {
            if (item.access_agency_id === this.clientId) {
              item.agency_id = item.service_id
              item.agency_name = item.service_agency_name
            }
            return item
          })
          if (this.isPro) {
            this.hangleChange(this.tableData?.[0]?.agency_id ?? '')
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    hangleChange(val) {
      const select = this.tableData.find(item => item.agency_id === val) || {}
      this.$emit('change', val)
      this.$emit('select', { ...select })
    },
  },
}
</script>

<style lang="scss" scoped></style>
